package com.chao.demo.server.Impl;

import com.chao.demo.bean.User;
import com.chao.demo.mapper.TestMapper;
import com.chao.demo.server.TestServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
public class TestServerImpl implements TestServer {

    @Autowired
    private TestMapper testMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public List<User> selectUserAll() {
        return testMapper.selectUserAll();
    }

    @Override
    public boolean addUser(User user) {
        return testMapper.addUser(user);
    }

    @Override
    public User updateUserStart(int userId) {
        testMapper.updateUserStart(userId);
        User user = testMapper.selectUserById(userId);
        return user;
    }

    @Override
    public boolean updateAccount() {
       return testMapper.updateAccount();
    }

    @Override
    public int getUserMonthSign() {
        //1. 获取登录用户
        int userId = 5;
        //2. 获取日期
        LocalDateTime now = LocalDateTime.now();
        //3. 拼接key
        String keySuffix = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String key = "sign" + userId + keySuffix;// sign5:202401
        //4. 获取今天是本月的第几天
        int dayOfMonth = now.getDayOfMonth();//12-1=11
        //5. 写入redis setbit key offset 1
        // stringRedisTemplate.opsForValue().setBit(key, 28, true);
        List<Long> result = stringRedisTemplate.opsForValue().bitField(
                key,
                BitFieldSubCommands.create()
                        .get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth)).valueAt(0)
        );
        if (result == null || result.isEmpty()) {
            // 没有任何签到结果
            return 0;
        }
        //num为0，直接返回0
        Long num = result.get(0);
        if (num == null || num == 0) {
            return 0;
        }
        // 6.循环遍历
        int count = 0;
        while (true) {
            // 6.1.让这个数字与1做与运算，得到数字的最后一个bit位  // 判断这个bit位是否为0
            if ((num & 1) == 0) {
                // 如果为0，说明未签到，结束
                break;
            }else {
                // 如果不为0，说明已签到，计数器+1
                count++;
            }
            // 把数字右移一位，抛弃最后一个bit位，继续下一个bit位
            num >>>= 1;
        }
        return count;
    }
    
    @Override
    public User getUserByAccount(String account) {
        return testMapper.selectUserByAccount(account);
    }
    
    @Override
    public User getUserByPhone(String phone) {
        return testMapper.selectUserByPhone(phone);
    }
}
